package com.ryan.security.browser;

import com.ryan.security.browser.support.SimpleResponse;
import com.ryan.security.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import sun.security.util.SecurityConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by kaimin on 1/1/2019.
 * time : 21:45
 */
@RestController
@Slf4j
public class BrowserSecurityController {

    //把当前的请求缓存，在具体的方法里面就可以判断，是不是 引发跳转的是html或者不是
    private RequestCache requestCache=new HttpSessionRequestCache();

    private RedirectStrategy redirectStrategy=new DefaultRedirectStrategy();
    //写一个需要身份认证的处理

    @Autowired
    private SecurityProperties securityProperties;
    /**
     * 需要身份认证的时候，跳转到这里，即BrowserSecutiryConfig 里loginPage需要改成这个，
     * 并且在这里判断，引发跳转的是html或者不是
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleResponse requireAuth(HttpServletRequest request, HttpServletResponse response){

        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if (savedRequest != null) {
            //拿到引发请求的url
            String redirectUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转的targetURL---》redirectUrl="+redirectUrl);
            if (StringUtils.endsWithIgnoreCase(redirectUrl, ".html")) {
                //是html，那么跳转到登录页
                try {
                    //不同的应用可能有不同的登录页，所以在demo应用里面指定，如果不指定，那么跳转到标准的登录页面
                    //所以利用系统配置完成登录页操作
                    redirectStrategy.sendRedirect(request,response,securityProperties.getBrowser().getLoginPage());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        return new SimpleResponse("访问的页面需要授权，请登录");
    }
}
